import threading
import time
from queue import Queue, Empty
import pyautogui
import keyboard  # 引入keyboard模块

from client.tdmg import manager


class MouseController:
    def __init__(self):
        self.queue = Queue()
        self.stop_event = threading.Event()
        self.pause_event = threading.Event()  # 暂停事件
        manager.start_thread(target=self.press_mouse_thread, args=(manager.get_stop_event(),))
        # self.thread = threading.Thread(target=self.press_mouse_thread)
        # self.thread.start()

        # 监听键盘事件'L'，按下时暂停所有事件
        keyboard.on_press_key('l', self.pause_resume_events)

    def press_mouse_thread(self,stop_event):
        while not stop_event.is_set():
            while self.pause_event.is_set():
                time.sleep(1)  # 暂停时每秒检查一次
            try:
                x, y, duration = self.queue.get(timeout=0.1)  # 从队列中获取鼠标事件
                self.execute_mouse_press(x, y, duration)
            except Exception as e:
                pass  # 可以根据需要处理队列异常
            time.sleep(0.1)  # 控制循环频率

    def execute_mouse_press(self, x, y, duration):
        pyautogui.moveTo(x, y)
        pyautogui.mouseDown(button='left')
        time.sleep(duration)
        pyautogui.mouseUp(button='left')

    def set_mouse(self, x, y, duration):
        self.clear_mouse()
        self.queue.put((x, y, duration))

    def clear_mouse(self):
        self.queue.queue.clear()

    def stop_mouse_press(self):
        self.queue.queue.clear()
        self.stop_event.set()
        # self.thread.join()

    def pause_resume_events(self, event):
        if self.pause_event.is_set():
            print("Resuming mouse events.")
            self.pause_event.clear()
        else:
            print("Pausing mouse events for 10 seconds.")
            self.pause_event.set()
            time.sleep(10)  # 暂停 10 秒钟
            self.pause_event.clear()
# class MouseController:
#     def __init__(self):
#         self.task_queue = Queue()
#         self.thread = threading.Thread(target=self.worker)
#         self.thread.daemon = True  # 设置为守护线程
#         self.thread.start()
#
#         self.cancel_event = threading.Event()  # 用于取消鼠标任务的事件
#
#         # 监听按键'L'，按下时设置取消事件
#         keyboard.on_press_key('l', self.cancel_mouse_tasks)
#
#     def worker(self):
#         while True:
#             try:
#                 task = self.task_queue.get(timeout=1)  # 获取任务
#                 if task is None:
#                     break
#                 x, y, hold_time = task
#                 self.perform_mouse_hold(x, y, hold_time)
#             except Empty:
#                 continue
#
#     def perform_mouse_hold(self, x, y, hold_time):
#         """
#         实现鼠标长按
#         :param x: 鼠标按下的x坐标
#         :param y: 鼠标按下的y坐标
#         :param hold_time: 按住鼠标的总时间（秒）
#         """
#         # 检查取消事件
#         if self.cancel_event.is_set():
#             print("Mouse tasks cancelled.")
#             self.cancel_event.clear()
#             time.sleep(10)  # 等待10秒
#             return
#
#         # 移动鼠标到指定位置
#         pyautogui.moveTo(x, y)
#         print(f"Mouse moved to ({x}, {y}).")
#
#         # 按下鼠标左键
#         pyautogui.mouseDown(x=x, y=y, button='left')
#         print(f"Left mouse button down at ({x}, {y}).")
#
#         # 等待按住时间
#         start_time = time.time()
#         while time.time() - start_time < hold_time:
#             # 检查取消事件
#             if self.cancel_event.is_set():
#                 pyautogui.mouseUp(x=x, y=y, button='left')
#                 print(f"Left mouse button up at ({x}, {y}).")
#                 self.cancel_event.clear()
#                 time.sleep(10)  # 等待10秒
#                 return
#             time.sleep(0.1)
#
#         # 松开鼠标左键
#         pyautogui.mouseUp(x=x, y=y, button='left')
#         print(f"Left mouse button up at ({x}, {y}).")
#
#     def cancel_mouse_tasks(self, event):
#         """
#         取消当前的鼠标任务
#         """
#         print("Cancel event detected. Cancelling current mouse tasks.")
#         self.cancel_event.set()
#
#     def cancel_all_mouse_tasks(self):
#         """
#         取消所有的鼠标任务
#         """
#         # 清空队列并设置取消事件
#         with self.task_queue.mutex:
#             self.task_queue.queue.clear()
#         # self.cancel_event.set()
#
#     def mouse_hold_and_cancel(self, x, y, hold_time=5):
#         """
#         添加鼠标操作任务到队列，并执行最新的任务
#         :param x: 鼠标按下的x坐标
#         :param y: 鼠标按下的y坐标
#         :param hold_time: 按住鼠标的总时间（秒）
#         """
#         # 清空队列，只保留最新的任务
#         with self.task_queue.mutex:
#             self.task_queue.queue.clear()
#
#         # 将最新任务放入队列
#         self.task_queue.put((x, y, hold_time))


# 示例：创建一个 MouseController 对象，并在指定坐标 (100, 200) 处长按鼠标左键5秒
# mouse_controller = MouseController()
# mouse_controller.mouse_hold_and_cancel(x=100, y=200, hold_time=5)
#
# # 模拟第二次点击
# time.sleep(2)  # 等待2秒，模拟第二次点击的时间间隔
# mouse_controller.mouse_hold_and_cancel(x=150, y=250, hold_time=3)
